package com.xiaofeng.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaofeng.subject.common.entity.PageResult;
import com.xiaofeng.subject.common.enums.IsDeletedFlagEnum;
import com.xiaofeng.subject.common.enums.SubjectLikedStatusEnum;
import com.xiaofeng.subject.common.utils.LoginUtil;
import com.xiaofeng.subject.domain.convert.SubjectLikedBOConverter;
import com.xiaofeng.subject.domain.entity.SubjectLikedBO;
import com.xiaofeng.subject.domain.redis.RedisUtil;
import com.xiaofeng.subject.domain.service.SubjectLikedDomainService;
import com.xiaofeng.subject.infra.basic.entity.SubjectLiked;
import com.xiaofeng.subject.infra.basic.service.SubjectLikedService;
import jdk.nashorn.internal.ir.ReturnNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: chc
 * @Date: 2024/03/04/16:32
 * @Description:
 */
@Service
@Slf4j
public class SubjectLikedDomainServiceImpl implements SubjectLikedDomainService {

    @Resource
    private SubjectLikedService subjectLikedService;

    @Resource
    private RedisUtil redisUtil;

    private static final String SUBJECT_LIKED_KEY = "subject.liked";

    private static final String SUBJECT_LIKED_COUNT_KEY = "subject.liked.count";

    private static final String SUBJECT_LIKED_DETAIL_KEY = "subject.liked.detail";

    @Override
    public void add(SubjectLikedBO subjectLikedBO) {
        Long subjectId = subjectLikedBO.getSubjectId();
        String likeUserId = subjectLikedBO.getLikeUserId();
        Integer status = subjectLikedBO.getStatus();
        String hashKey = buildSubjectLikedKey(subjectId.toString(), likeUserId);
        redisUtil.putHash(SUBJECT_LIKED_KEY,hashKey,status);
        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + likeUserId;
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;
        //点赞操作
        if (SubjectLikedStatusEnum.PRIMARY.getCode() == status){
            //点赞加1操作
            redisUtil.increment(countKey,1);
            //设置每个用户只能对该题目点赞一次，不可以重复点赞
            redisUtil.set(detailKey,"1");
        }else { //取消操作
            //获取点赞数量
            Integer count = redisUtil.getInt(countKey);
            //为空的话返回，不为空往下继续执行
            if (Objects.isNull(count) || count <= 0){
                return;
            }
            //点赞数量减1
            redisUtil.increment(countKey,-1);
            //用户取消点赞，所有该用户唯一信息也要删除
            redisUtil.del(detailKey);
        }
    }

    private String buildSubjectLikedKey(String subjectId,String userId){
        return subjectId + ":" + userId;
    }

    /**
     * 判断改题目是否被点过赞
     * @param subjectId
     * @param userId
     * @return
     */
    @Override
    public Boolean isLiked(String subjectId, String userId) {
        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + userId;
        return redisUtil.exist(detailKey);
    }

    /**
     * 从redis中获取该题目的点赞数量
     * @param subjectId
     * @return
     */
    @Override
    public Integer getLikedCount(String subjectId) {
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;
        Integer count = redisUtil.getInt(countKey);
        if (Objects.isNull(count) || count <= 0){
            return 0;
        }
        return redisUtil.getInt(countKey);
    }

    @Override
    public Boolean update(SubjectLikedBO subjectLikedBO) {
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        return subjectLikedService.update(subjectLiked) > 0;
    }

    @Override
    public Boolean delete(SubjectLikedBO subjectLikedBO) {
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        subjectLiked.setId(subjectLikedBO.getId());
        subjectLiked.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        return subjectLikedService.update(subjectLiked) > 0;
    }

    @Override
    public void syncLiked() {
        Map<Object, Object> subjectLikedMap = redisUtil.getHashAndDelete(SUBJECT_LIKED_KEY);
        if (log.isInfoEnabled()){
            log.info("syncLiked.subjectLikedMap:{}", JSON.toJSONString(subjectLikedMap));
        }
        if (MapUtils.isEmpty(subjectLikedMap)){
            return;
        }
        //批量同步到数据库
        LinkedList<SubjectLiked> subjectLikedList = new LinkedList<>();
        //循环遍历
        subjectLikedMap.forEach((key,val) ->{
            SubjectLiked subjectLiked = new SubjectLiked();
            String[] keyArr = key.toString().split(":");
            String subjectId =keyArr[0];
            String likedUser =keyArr[1];
            subjectLiked.setSubjectId(Long.valueOf(subjectId));
            subjectLiked.setLikeUserId(likedUser);
            subjectLiked.setStatus(Integer.valueOf(val.toString()));
            subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectLikedList.add(subjectLiked);
        });
        //批量同步更新或插入
        subjectLikedService.batchInsertOrUpdate(subjectLikedList);
    }

    @Override
    public PageResult<SubjectLikedBO> getSubjectLikedPage(SubjectLikedBO subjectLikedBO) {
        PageResult<SubjectLikedBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectLikedBO.getPageNo());
        pageResult.setPageSize(subjectLikedBO.getPageSize());
        int start = (subjectLikedBO.getPageNo() - 1) * subjectLikedBO.getPageSize();
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        subjectLiked.setLikeUserId(LoginUtil.getLoginId());
        int count = subjectLikedService.countByCondition(subjectLiked);
        if (count == 0){
            return pageResult;
        }
        List<SubjectLiked> subjectLikedList = subjectLikedService.queryPage(subjectLiked,start,subjectLikedBO.getPageSize());
        List<SubjectLikedBO> subjectLikedBOS = SubjectLikedBOConverter.INSTANCE.convertListInfoToBO(subjectLikedList);
        pageResult.setRecords(subjectLikedBOS);
        pageResult.setTotal(count);
        return pageResult;
    }
}
